package com.cw.realtime.common
package util

import constant.Constant.{MYSQL_DRIVER, MYSQL_PASSWORD, MYSQL_URL, MYSQL_USER_NAME}

import java.sql.{Connection, DriverManager, ResultSet}
import scala.collection.mutable.ListBuffer
import scala.language.experimental.macros

trait Queryable[T] {
  def decode(result: ResultSet): T
}


object Queryable {


  //  def createCaseClass[T]: ResultSet => T = createCaseClass4Jdbc

}


object JdbcUtil {


  def getMysqlConnection: Option[Connection] = {
    // 获取 jdbc 连接
    // 1. 加载驱动
    Class.forName(MYSQL_DRIVER);
    Option(DriverManager.getConnection(MYSQL_URL, MYSQL_USER_NAME, MYSQL_PASSWORD))
  }


  def queryList[T: Queryable](conn: Connection, sql: String): List[T] = {
    val lb = ListBuffer.empty[T]
    val preStatement = conn.prepareStatement(sql)
    val res = preStatement.executeQuery()
    while (res.next()) {
      lb += implicitly[Queryable[T]].decode(res)
    }
    lb.toList
  }


  def closeConnection(conn: Connection): Unit =
    if (!conn.isClosed) conn.close()


}
